package com.xiaomo.gitee.datamanager.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

@SuppressWarnings("unchecked")
public class AnnotationUtils {

    public static <T extends Annotation> T createAnnotationInstance(Class<T> annotation, Map<String, Object> values) {
        return (T) Proxy.newProxyInstance(annotation.getClassLoader(), new Class[]{annotation},
                new MyAnnotationInvocationHandler(values));
    }

    private record MyAnnotationInvocationHandler(Map<String, Object> map) implements InvocationHandler {

        @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = map.get(method.getName());
                if (result != null) {
                    return result;
                }
                return method.getDefaultValue();
            }
        }

}
